package com.boot.security.server.service.impl.mffl.MfflLawyerletter;


import com.boot.security.server.dao.mffl.*;
import com.boot.security.server.model.SysUser;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.model.mffl.Vo.MfflLawyerletterVo;
import com.boot.security.server.service.impl.mffl.LwyerPersonalService.LwyerPersonalService;
import com.boot.security.server.service.impl.mffl.MfflLawyerComment.MfflLawyerCommentService;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

import com.boot.security.server.service.impl.mffl.Lawyerservicepeoplenumber.LawyerservicepeoplenumberService;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;
import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;

/**
 * 律师函service
 */
@Service
public class MfflLawyerletterService {

    //配置微信支付随机数
    @Value("${Pay.attach}")
    private String attach;

    @Autowired
    private MfflLawyerletterDao mfflLawyerletterDao;

    //类型
    @Autowired
    private MfflTypeDao mfflTypeDao;

    //律师个人服务收费
    @Autowired
    private MfflLwyerPersonalServiceDao mfflLwyerPersonalServiceDao;

    //律师收费标准
    @Autowired
    private LwyerPersonalService lwyerPersonalservice;

    //订单
    @Autowired
    private MfflOrderDao mfflOrderDao;

    //微信支付
    @Autowired
    private WXPayService wxpayservice;

    //服务类型表
    @Autowired
    MfflServiceDao Mfflservicedao;

    //支入支出表
    @Autowired
    private MfflProfitDao mfflProfitDao;

    //用户表
    @Autowired
    MfflUserDao mffluserdao;

    //快递公司
    @Autowired
    private MfflCourierServicesCompanyDao mfflCourierServicesCompanyDao;

    //快递订单表
    @Autowired
    private MfflCourierServicesOrderDao mfflCourierServicesOrderDao;

    //服务
    @Autowired
    MfflServiceDao mfflservicedao;

    //评论
    @Autowired
    MfflLawyerCommentService mfflLawyercommentservice;

    //退款表
    @Autowired
    MfflRefundDao mfflRefundDao;

    //服务人数
    @Autowired
    LawyerservicepeoplenumberService LawyerservicepeoplenumberService;

    //推送
    @Autowired
    private MfflSystemMessagesImpl MfflSystemMessagesImpl;
    //公共功能
    @Autowired
    private publicService publicService;


    //保存律师函
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean save(Integer typeid, String Realname, String number, String describe, String imageUrl, String We, String otherParty, String content, Integer serviceLawyerId) throws Exception {
        try {
            ReturnBean returnBean;
            //获取当前用户
            SysUser sysUser = UserUtil.getLoginUser();

            //判断律师是否存在
            mfflUserSimple lawyer = mffluserdao.getLawyer(serviceLawyerId);
            if (lawyer == null) {
                ReturnBean returnBean1 = new ReturnBean();
                returnBean1.setReturnBean("116");
                return returnBean1;
            }

            //查看律师是否通过认证
            if (lawyer.getLawyerinspect() != 1) {
                returnBean = new ReturnBean();
                returnBean.setReturnBean("137");
                return returnBean;
            }

            //判断该类型是否存在
            if (mfflTypeDao.getByTypeId(typeid, 2) == null) {
                ReturnBean returnBean1 = new ReturnBean();
                returnBean1.setReturnBean("110");
                return returnBean1;
            }

            //创建律师函
            MfflLawyerletter mfflLawyerletter = new MfflLawyerletter();
            //查看律师收费标准，并设置收费标准
            Integer lawyerId = serviceLawyerId;
            Integer serviceId = 3;
            Integer typeId = typeid;
            MfflLwyerPersonalService mll = lwyerPersonalservice.getLawyerServiceMoney(lawyerId, serviceId);//查询律师收费情况
            //律师未设置收费标准
            if (mll == null) {
                returnBean = new ReturnBean();
                returnBean.setReturnBean("112");
                return returnBean;
            }
            mfflLawyerletter.setTypeId(typeid);
            mfflLawyerletter.setServiceId(3);
            mfflLawyerletter.setDescribe(describe);
            mfflLawyerletter.setImageUrl(imageUrl == null ? "" : imageUrl);
            mfflLawyerletter.setRealname(Realname);
            mfflLawyerletter.setNumber(number);
            mfflLawyerletter.setPayId(0);
            mfflLawyerletter.setPayNumber("");
            String payMerchantNumber = ProjectUtil.payMerchantNumber(); //获取商户订单号
            mfflLawyerletter.setPayMerchantNumber(payMerchantNumber);
            mfflLawyerletter.setServiceLawyerId(serviceLawyerId);
            mfflLawyerletter.setPayState(0);                            //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mfflLawyerletter.setState(0);                               //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mfflLawyerletter.setFile("");
            mfflLawyerletter.setCreateTime(new Date());
            mfflLawyerletter.setUpdateTime(new Date());
            mfflLawyerletter.setDeleteState(1);
            mfflLawyerletter.setDeleteTime(new Date());
            mfflLawyerletter.setWe(We);                                 //我方
            mfflLawyerletter.setOtherParty(otherParty);
            mfflLawyerletter.setContent(content == null ? "" : content);
            mfflLawyerletter.setAddRessee("");
            mfflLawyerletter.setRecipientPhoneNumber("");
            mfflLawyerletter.setAddress("");
            mfflLawyerletter.setCourierCompanyId(0);
            mfflLawyerletter.setCourierNumber("");
            mfflLawyerletter.setSender("");
            mfflLawyerletter.setOriginatingPlace("");
            mfflLawyerletter.setSenderPhone("");
            mfflLawyerletter.setPaymentTime(new Date());
            mfflLawyerletter.setMoney(mll.getMoney());
            mfflLawyerletter.setUserId(sysUser.getId().intValue());
            mfflLawyerletter.setConfirmTime(ProjectUtil.getinitialTime());      //初始时间
            mfflLawyerletter.setRefuseTime(ProjectUtil.getinitialTime());       //初始时间
            mfflLawyerletter.setCommentState(0);                                //是否评论状态0未评论1评论
            int saveLawyerletter = mfflLawyerletterDao.save(mfflLawyerletter);

            //创建订单
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setPayNumber("");
            mfflOrder.setPayMerchantNumber(payMerchantNumber);  //获取商户订单号
            mfflOrder.setServierId(3);                          //3为律师函
            mfflOrder.setServiceName("律师函");                  //服务名称
            mfflOrder.setMoney(mll.getMoney());                 //金额
            mfflOrder.setUserid(sysUser.getId().intValue());
            mfflOrder.setCreateTime(new Date());
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setDeleteTime(new Date());
            mfflOrder.setDeleteStae(1);                         //是否删除(0删除,1正常)
            mfflOrder.setTypeid(typeId);                        //类型
            mfflOrder.setState(0);                              //0待支付，1支付，2退款
            Long ProductId = mfflLawyerletter.getId();
            mfflOrder.setProductId(ProductId.intValue());       //订单关联
            int saveOrderDao = mfflOrderDao.save(mfflOrder);

            //律师函关联订单
            MfflLawyerletter mfll = new MfflLawyerletter();
            mfll.setId(mfflLawyerletter.getId());
            mfll.setPayId(mfflOrder.getId().intValue());
            mfflLawyerletterDao.update(mfll);

            returnBean = new ReturnBean();
            if (saveLawyerletter == 1 && saveOrderDao == 1) {
                returnBean.setReturnBean("200");
                returnBean.setDatas(payMerchantNumber);
            } else {
                returnBean.setReturnBean("105");
            }
            return returnBean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("异常错误");
        }
    }

    /**
     * 查询订单状态
     * <p>
     * 如果查询微信订单为已支付并且本地order未改变，则修改状态
     *
     * @param payMerchantNumber
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean orderquery(String payMerchantNumber) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        try {
            Map<String, String> orderquery = wxpayservice.orderquery(payMerchantNumber);
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(payMerchantNumber);
            if (!(orderquery.containsKey("trade_state") && orderquery.get("trade_state").equals("SUCCESS")) || Order.getState() == 0) {
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setState(5);//支付中
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrderDao.update(mfflOrder);
                returnbean.setDatas(orderquery);
                return returnbean;
            }

            //订单操作
            String payNumber = orderquery.get("transaction_id");
            //律师函状态
            MfflLawyerletter lawyerLetter = mfflLawyerletterDao.getById(Order.getProductId().longValue());
            //如果状态未改变则改变状态
            if (lawyerLetter.getPayState() == 0 || (Order.getState() == 0 || Order.getState() == 5)) {
                //创建一个实体，防止在修改过程中其他信息改变的风险
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setPayNumber(payNumber);
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrder.setState(1);
                mfflOrderDao.update(mfflOrder);


                //创建一个实体，防止在修改过程中其他信息改变的风险
                MfflLawyerletter ml = new MfflLawyerletter();
                ml.setId(lawyerLetter.getId());
                if (lawyerLetter.getPayId() == null || lawyerLetter.getPayId() == 0) {
                    ml.setPayId(mfflOrder.getId().intValue());
                }
                ml.setPayNumber(payNumber);
                //ml.setState(1);   //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
                ml.setPayState(1);//支付状态:0.待支付1.已支付2.已退款3.申请退款
                ml.setPaymentTime(new Date());

                //确认拒绝服务时间（律师多久无反应后，视为拒绝服务）
                MfflService byId = mfflservicedao.getById((long) lawyerLetter.getServiceId());
                long t1 = System.currentTimeMillis();
                long t2 = Long.valueOf(byId.getRefuseTime());
                Date dateTime = new Date();
                dateTime.setTime(t1 + t2);
                ml.setRefuseTime(dateTime);
                mfflLawyerletterDao.update(ml);

                //用户支出信息
                //金额来自律师个人服务项目，扣点来自服务表
                //double points = ProjectUtil.Points(mll.getMoney(), ms.getPoints());
                //插入 支入支出表
                List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
                if (byOrderId.size() == 0) {
                    MfflProfit mp = new MfflProfit();
                    mp.setOrderId(mfflOrder.getId().intValue());
                    mp.setUserId(lawyerLetter.getUserId()); //用户id
                    mp.setServciceName("律师函");
                    mp.setState(0);               //0支出，1收益,
                    mp.setMoney(lawyerLetter.getMoney());  //支出不扣点
                    mp.setSettlement(1);          //0未结算，1已经算
                    mp.setCreateTime(new Date());
                    mp.setSettlementTime(new Date());
                    mp.setDeduction(0.0);
                    mp.setUpdateTime(new Date());
                    mfflProfitDao.save(mp);

                    //律师支出
                    MfflProfit mlp = new MfflProfit();
                    mlp.setOrderId(Order.getId().intValue());
                    mlp.setUserId(lawyerLetter.getServiceLawyerId()); //律师id
                    mlp.setServciceName("律师函");
                    mlp.setState(1);               //0支出，1收益,
                    mlp.setMoney(lawyerLetter.getMoney());   //律师收益显示已扣点金额
                    mlp.setSettlement(0);          //0未结算，1已经算
                    mlp.setCreateTime(new Date());
                    mlp.setSettlementTime(new Date());
                    mlp.setDeduction(0.0);   //平台扣点金额
                    mlp.setUpdateTime(new Date());
                    mfflProfitDao.save(mlp);
                }
                return returnbean;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("异常错误");
        }
        return returnbean;
    }


    //微信支付
    public ReturnBean LawyerletterServicePay(String payMerchantNumber, String notifyurl) {

        if (mfflLawyerletterDao.getBypaymerchantnumber(payMerchantNumber) == null) {
            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("106");
            returnbean.setMessage("当前商户号对应的，律师函不存在");
            return returnbean;
        }

        ReturnBean returnBean = wxpayservice.WXPay(notifyurl, "律师函", payMerchantNumber);
        if ("123".equals(returnBean.getErrCode())) {
            //订单号重复支付修改订单号，修改数据订单号
            //修改合同订单号  修改order订单号
            //订单操作
            MfflOrder Order = mfflOrderDao.getBypaymerchantnumber(payMerchantNumber);

            //律师函
            MfflLawyerletter lawyerLetter = mfflLawyerletterDao.getById(Order.getProductId().longValue());

            //重新生成订单号
            String newpayMerchantNumber = ProjectUtil.payMerchantNumber();

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayMerchantNumber(newpayMerchantNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrderDao.update(mfflOrder);

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflLawyerletter ml = new MfflLawyerletter();
            ml.setId(lawyerLetter.getId());
            ml.setPayMerchantNumber(newpayMerchantNumber);
            ml.setUpdateTime(new Date());
            mfflLawyerletterDao.update(ml);
            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("142");
            returnbean.setDatas(new HashMap<String, String>() {{
                put("newpayMerchantNumber", newpayMerchantNumber);
            }});
            return returnbean;
        }
        return returnBean;
    }


    //微信支付回调
    @Transactional(rollbackFor = Exception.class)
    public boolean WechatPayCallback(Map<String, String> map) throws Exception {
        System.out.println("访问回调");
        System.out.println(map);
        String paymerchantnumber = map.get("out_trade_no");//商户订单号
        String payNumber = map.get("transaction_id");      //交易单号

        String nonceStr = map.get("attach");      //随机数

        //验证随机数
        if (!attach.equals(nonceStr)) {
            System.out.println("验证随机数不通过");
            return false;
        }

        try {
            //订单操作
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(paymerchantnumber);
            //律师函状态
            MfflLawyerletter lawyerLetter = mfflLawyerletterDao.getById(Order.getProductId().longValue());
            //如果已支付返回true
            if (lawyerLetter.getPayState() != 0 && !(Order.getState() == 0 || Order.getState() == 5)) {
                return true;
            }
            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayNumber(payNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(1);
            mfflOrderDao.update(mfflOrder);


            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflLawyerletter ml = new MfflLawyerletter();
            ml.setId(lawyerLetter.getId());
            if (StringUtils.isEmpty(lawyerLetter.getPayId()) || lawyerLetter.getPayId() == 0) {
                ml.setPayId(mfflOrder.getId().intValue());
            }
            ml.setPayNumber(payNumber);
            //ml.setState(1);   //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            ml.setPayState(1);//支付状态:0.待支付1.已支付2.已退款3.申请退款
            ml.setPaymentTime(new Date());

            //确认拒绝服务时间（律师多久无反应后，视为拒绝服务）
            MfflService byId = mfflservicedao.getById((long) lawyerLetter.getServiceId());
            long t1 = System.currentTimeMillis();
            long t2 = Long.valueOf(byId.getRefuseTime());
            Date dateTime = new Date();
            dateTime.setTime(t1 + t2);
            ml.setRefuseTime(dateTime);
            mfflLawyerletterDao.update(ml);


            //用户支出信息
            //金额来自律师个人服务项目，扣点来自服务表
            //double points = ProjectUtil.Points(mll.getMoney(), ms.getPoints());
            //插入 支入支出表
            List<MfflProfit> byOrderId = mfflProfitDao.getOrderId(mfflOrder.getId().intValue());
            if (byOrderId.size() == 0) {
                MfflProfit mp = new MfflProfit();
                mp.setOrderId(mfflOrder.getId().intValue());
                mp.setUserId(lawyerLetter.getUserId()); //用户id
                mp.setServciceName("律师函");
                mp.setState(0);               //0支出，1收益,
                mp.setMoney(lawyerLetter.getMoney());  //支出不扣点
                mp.setSettlement(1);          //0未结算，1已经算
                mp.setCreateTime(new Date());
                mp.setSettlementTime(new Date());
                mp.setDeduction(0.0);
                mp.setUpdateTime(new Date());
                mfflProfitDao.save(mp);

                //律师支出
                MfflProfit mlp = new MfflProfit();
                mlp.setOrderId(Order.getId().intValue());
                mlp.setUserId(lawyerLetter.getServiceLawyerId()); //律师id
                mlp.setServciceName("律师函");
                mlp.setState(1);               //0支出，1收益,
                mlp.setMoney(lawyerLetter.getMoney());   //律师收益显示已扣点金额
                mlp.setSettlement(0);          //0未结算，1已经算
                mlp.setCreateTime(new Date());
                mlp.setSettlementTime(new Date());
                mlp.setDeduction(0.0);   //平台扣点金额
                mlp.setUpdateTime(new Date());
                mfflProfitDao.save(mlp);
                MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]一条新的律师函业务", lawyerLetter.getPayMerchantNumber()), lawyerLetter.getServiceId().toString(), lawyerLetter.getId().intValue(), lawyerLetter.getServiceLawyerId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            //防止意外错误
            //return false;
            throw new Exception("微信回调异常");
        }
        return true;
    }


    /**
     * 用户添加邮件地址信息
     *
     * @param id                   订单id
     * @param addRessee            收件人
     * @param recipientPhoneNumber 联系电话
     * @param address              收件地址
     * @return 修改状态
     */
    public ReturnBean writeEmailInfo(Integer id, String addRessee, String recipientPhoneNumber, String address) {
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        MfflLawyerletter byId = mfflLawyerletterDao.getById(id.longValue());
        if (sysUser.getId().intValue() != byId.getUserId()) {
            return new ReturnBean("201", "此律师函,不属于该用户");
        }
        ReturnBean returnbean = new ReturnBean();
        if (byId == null) {
            returnbean.setReturnBean("106");
            return returnbean;
        }

        if (byId.getState() > 1) {
            return new ReturnBean("201", "订单不是发布状态，无法添加信息");
        }

        //查看律师是否通过认证
        MfflUser lawyer = mffluserdao.getByUserId(byId.getServiceLawyerId().longValue());
        if (lawyer.getLawyerInspect() != 1) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("137");
            return returnBean;
        }

        MfflLawyerletter ml = new MfflLawyerletter();
        ml.setId(byId.getId());
        ml.setAddRessee(addRessee);
        ml.setRecipientPhoneNumber(recipientPhoneNumber);
        ml.setAddress(address);
        int update = mfflLawyerletterDao.update(ml);
        if (update != 1) {
            returnbean.setReturnBean("105");
            return returnbean;
        }
        returnbean.setReturnBean("200");
        return returnbean;
    }


    /**
     * 律师发送邮件
     *
     * @param id               律师函id
     * @param courierId        快递id
     * @param courierNumber    快递单号
     * @param Sender           发件人姓名
     * @param originatingPlace 发件人地址
     * @param SenderPhone      发件人电话
     * @return
     */
    @Transactional
    public ReturnBean LawyerSendMail(Integer id, Integer courierId, String courierNumber, String Sender, String originatingPlace, String SenderPhone) {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();

        //判断各项信息是否正常

        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (StringUtils.isEmpty(mll.getAddRessee()) || StringUtils.isEmpty(mll.getRecipientPhoneNumber()) || StringUtils.isEmpty(mll.getAddress())) {
            returnbean.setReturnBean("120");
            return returnbean;
        }

        //快递公司是否存在
        MfflCourierServicesCompany msv = mfflCourierServicesCompanyDao.getById(courierId.longValue());
        if (msv == null) {
            return new ReturnBean("201", "快递公司不存在");
        }

        //判断当前律师是否，是负责当前律师函的律师
        if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "当前律师不是,负责此律师函的律师");
        }

        //查看律师是否通过认证
        MfflUser lawyer = mffluserdao.getByUserId(mll.getServiceLawyerId().longValue());
        if (lawyer.getLawyerInspect() != 1) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("137");
            return returnBean;
        }

        //添加一个快递信息
        MfflCourierServicesOrder mso = new MfflCourierServicesOrder();
        mso.setIelationId(mll.getId().intValue());
        mso.setIelationServiceName("律师函");
        mso.setIelationtype(3);
        mso.setSender(Sender);
        mso.setOriginatingPlace(originatingPlace);
        mso.setSenderPhone(SenderPhone);
        mso.setCourierCompanyId(msv.getId().intValue());
        mso.setCourierNumber(courierNumber);
        mso.setCreateTime(new Date());
        mso.setUpdateTime(new Date());
        mfflCourierServicesOrderDao.save(mso);

        //律师函信息寄送方信息
        MfflLawyerletter newmll = new MfflLawyerletter();
        newmll.setId(mll.getId());
        newmll.setState(3);//订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")

        //设置时间多久后自动确认收货
        /*MfflService byId = Mfflservicedao.getById((long) 3);
        long t1 = System.currentTimeMillis();
        long t2 = Long.valueOf(byId.getConfirmTime());
        Date date = new Date();
        date.setTime(t1 + t2);*/

        newmll.setConfirmTime(new Date()); //开始计时
        mfflLawyerletterDao.update(newmll);

        MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]律师已发送邮件", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getUserId());
        return returnbean;
    }


    /**
     * 律师修改邮件
     *
     * @param id               律师函id
     * @param Sendingid        快递id
     * @param courierId        快递公司id
     * @param courierNumber    快递单号
     * @param Sender           发件人姓名
     * @param originatingPlace 发件人地址
     * @param SenderPhone      发件人电话
     * @return
     */
    @Transactional
    public ReturnBean LawyerUpdateMail(Integer id, Integer Sendingid, Integer courierId, String courierNumber, String Sender, String originatingPlace, String SenderPhone) {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();

        //判断各项信息是否正常

        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (mll.getState() != 3) {
            return new ReturnBean("201", "当前状态不允许修改物流信息");
        }

        if (StringUtils.isEmpty(mll.getAddRessee()) || StringUtils.isEmpty(mll.getRecipientPhoneNumber()) || StringUtils.isEmpty(mll.getAddress())) {
            returnbean.setReturnBean("120");
            return returnbean;
        }

        //快递公司是否存在
        MfflCourierServicesCompany msv = mfflCourierServicesCompanyDao.getById(courierId.longValue());
        if (msv == null) {
            return new ReturnBean("201", "快递公司不存在");
        }

        //判断当前律师是否，是负责当前律师函的律师
        if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "当前律师不是,负责此律师函的律师");
        }

        //查看律师是否通过认证
        MfflUser lawyer = mffluserdao.getById(mll.getServiceLawyerId().longValue());
        if (lawyer.getLawyerInspect() != 1) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("137");
            return returnBean;
        }


        MfflCourierServicesOrder CourierServicesOrder = mfflCourierServicesOrderDao.getById(Sendingid.longValue());
        //判断当前律师是否，是负责当前律师函的律师
        if (CourierServicesOrder == null) {
            return new ReturnBean("201", "要修改的快递信息不存在");
        }

        //修改一个快递信息
        MfflCourierServicesOrder mso = new MfflCourierServicesOrder();
        mso.setId(CourierServicesOrder.getId());
        mso.setSender(Sender);
        mso.setOriginatingPlace(originatingPlace);
        mso.setSenderPhone(SenderPhone);
        mso.setCourierCompanyId(msv.getId().intValue());
        mso.setCourierNumber(courierNumber);
        mso.setUpdateTime(new Date());
        mfflCourierServicesOrderDao.update(mso);
        return returnbean;
    }


    /**
     * @param type 0律师拨打用户，1用户拨打律师
     * @param id
     * @return
     */
    public ReturnBean Phone(Integer type, Integer id) {
        ReturnBean returnBean = new ReturnBean();
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (type == 0) {
            returnBean.setReturnBean("200");
            returnBean.setDatas(StringUtils.isEmpty(mll.getRecipientPhoneNumber()) ? "对方未填写收件信息" : mll.getRecipientPhoneNumber());
        } else {
            returnBean.setReturnBean("200");
            returnBean.setDatas(StringUtils.isEmpty(mll.getSenderPhone()) ? "对方未填写收件信息" : mll.getSenderPhone());
        }
        return returnBean;
    }

    /**
     * @param id 律师函id
     * @return 快递信息
     */
    public ReturnBean<MfflCourierServicesOrder> showCourier(Integer id) {
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }
        //快递公司是否存在
        /*MfflCourierServicesCompany msv = mfflCourierServicesCompanyDao.getById(mll.getCourierCompanyId().longValue());
        if (msv == null) {
            return new ReturnBean("201", "快递公司不存在");
        }*/

        List<MfflCourierServicesOrder> List = mfflCourierServicesOrderDao.getByIelationId(mll.getId().intValue(), 3);
        for (MfflCourierServicesOrder item : List) {
            item.setMfflCourierServicesCompany(mfflCourierServicesCompanyDao.getById(item.getCourierCompanyId().longValue()));
        }
        ReturnBean returnbean = new ReturnBean();
        returnbean.setDatas(List);
        returnbean.setReturnBean("200");
        return returnbean;
    }

    /**
     * 按id查询律师函快递信息
     *
     * @return 快递信息
     * @id 律师函id
     * @courierid 快递id
     */
    public ReturnBean<MfflCourierServicesOrder> showCourierbyid(Integer id, Integer courierid) {
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }
        MfflCourierServicesOrder Courier = mfflCourierServicesOrderDao.getById(courierid.longValue());
        if (Courier == null) {
            return new ReturnBean("201", "快递信息不存在");
        }
        Courier.setMfflCourierServicesCompany(mfflCourierServicesCompanyDao.getById(Courier.getCourierCompanyId().longValue()));
        ReturnBean returnbean = new ReturnBean();
        returnbean.setDatas(Courier);
        returnbean.setReturnBean("200");
        return returnbean;
    }


    /**
     * 确认完成
     *
     * @param lawyerletterId 律师函id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean ConfirmCompletion(Integer lawyerletterId) throws Exception {

        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(lawyerletterId.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (mll.getUserId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "该律师函不属于本用户");
        }

        //判断收货状态
        if (mll.getState() != 3) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行确认完成操作");
            return returnbean;
        }

        //查看律师是否通过认证
        MfflUser userInfoAll = mffluserdao.getmffluser(mll.getServiceLawyerId());
        if (userInfoAll.getLawyerInspect() != 1) {
            ReturnBean returnBean = new ReturnBean();
            returnBean.setReturnBean("137");
            return returnBean;
        }

        try {
            //修改律师函状态
            MfflLawyerletter mllt = new MfflLawyerletter();
            mllt.setId(mll.getId());
            mllt.setState(4);       //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
            mfflLawyerletterDao.update(mllt);

            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());

            Integer orderid;
            Integer userId;
            //获取支入支出表---用户
            orderid = mo.getId().intValue();
            userId = sysUser.getId().intValue();
            MfflProfit userProfit = mfflProfitDao.getByOrderId(orderid, userId);

            //获取支入支出表---律师
            userId = mll.getServiceLawyerId();
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(orderid, userId);


            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(1);          //0未结算，1已经算
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);


            //修改律师个人账户金额


            MfflUser mu = new MfflUser();
            mu.setId(userInfoAll.getId());
            mu.setMoney(ProjectUtil.addition(userInfoAll.getMoney(), mo.getMoney()));
            mu.setUpdateTime(new Date());
            mffluserdao.update(mu);

            //增加服务人数
            LawyerservicepeoplenumberService.increaseLawyerservicepeoplenumber(userInfoAll.getId().intValue());
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]用户确认完成", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
        } catch (Exception e) {
            e.printStackTrace();
            //returnbean.setReturnBean("105");
            //return returnbean;
            throw new Exception("确认完成");
        }
        returnbean.setReturnBean("200");
        return returnbean;
    }


    /**
     * 按照id查看律师函
     *
     * @param id 律师函id
     * @return
     */
    public ReturnBean<MfflLawyerletterVo> getIdlawyerletter(Integer id) {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //律师函是否存在
        MfflLawyerletterVo mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        //多图片处理图片处理
        if (!StringUtils.isEmpty(mll.getImageUrl())) {
            List<Map<String, Object>> maps = new ArrayList<>();
            String[] split = mll.getImageUrl().split(";");
            for (String time : split) {
                if (StringUtils.isEmpty(time) || time.equals("undefined")) {
                    continue;
                }
                Map<String, Object> map = ProjectUtil.imageUrlAll(time);
                maps.add(map);

            }
            mll.setImageUrlAll(maps);
        }


        try {
            //查询律师信息
            mfflUserSimple lawyerinfo = mffluserdao.getUserInfoSimple(mll.getServiceLawyerId());
            //用户信息
            mfflUserSimple userinfo = mffluserdao.getUserInfoSimple(mll.getUserId());
            //快递信息
            List<MfflCourierServicesOrder> List = mfflCourierServicesOrderDao.getByIelationId(mll.getId().intValue(), 3);
            for (MfflCourierServicesOrder item : List) {
                item.setMfflCourierServicesCompany(mfflCourierServicesCompanyDao.getById(item.getCourierCompanyId().longValue()));
            }
            mll.setLaywerinfo(lawyerinfo);
            mll.setUserinfo(userinfo);
            mll.setCourierServicesOrder(List);
        } catch (Exception e) {
            e.printStackTrace();
            returnbean.setReturnBean("105");
            return returnbean;
        }

        returnbean.setReturnBean("200");
        returnbean.setDatas(mll);
        return returnbean;
    }


    /**
     * 撤销发布
     *
     * @param id 律师函id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean cancelLawyerletter(long id) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id);
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (mll.getUserId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "该律师函不属于本用户");
        }
        //判断收货状态
        if (mll.getState() != 0) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行撤销发布操作");
            return returnbean;
        }

        //获取订单信息
        MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());


        //获取支入支出表---用户
        MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());

        //获取支入支出表---律师
        MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());

        //未支付状态
        if (mo.getState() == 0) {
            //更新订单信息
            MfflLawyerletter mllr = new MfflLawyerletter();
            mllr.setId(id);
            //mllr.setDeleteState(0);
            mllr.setState(5);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
            //mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            mfflLawyerletterDao.update(mllr);

            MfflOrder mffd = new MfflOrder();
            mffd.setId(mo.getId());
            mffd.setDeleteStae(0);
            Date date = new Date();
            mffd.setUpdtaeTime(date);
            mffd.setState(2);
            mfflOrderDao.update(mffd);
            return returnbean;
        }


        //退款操作
        ReturnBean returnBean = wxpayservice.weChatrefund(mo.getPayMerchantNumber(), null, "撤销发布", 0);
        if (!"200".equals(returnBean.getErrCode())) {
            return returnBean;
        }

        //更新订单信息
        MfflLawyerletter mllr = new MfflLawyerletter();
        mllr.setId(id);
        //mllr.setDeleteState(0);
        mllr.setState(5);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
        mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
        mllr.setUpdateTime(new Date());
        mfflLawyerletterDao.update(mllr);


        //修改双方支付支出表--用户
        MfflProfit mp = new MfflProfit();
        mp.setId(userProfit.getId());
        mp.setSettlement(2);
        mp.setUpdateTime(new Date());
        mfflProfitDao.update(mp);

        //修改双方支付支出表--律师
        MfflProfit mlp = new MfflProfit();
        mlp.setId(lawyerProfit.getId());
        mlp.setSettlement(2);          //0未结算，1已经算 ， 2退款，3 申请退款
        mlp.setUpdateTime(new Date());
        mfflProfitDao.update(mlp);

        MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]用户撤销发布", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
        return returnbean;
    }


    /**
     * 申请退款操作
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean refund(Long id, String refundreason) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id);
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (mll.getUserId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "该律师函不属于本用户");
        }
        //获取订单信息
        MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());
        //判断当前状态
        if (mo.getState() == 2 || mo.getState() == 4 || mo.getState() == 5 || mo.getState() == 0 || mll.getPayState() == 2 || mll.getPayState() == 3 || mll.getState() == 7 || mll.getState() == 6 || mll.getState() == 5 || mll.getState() == 4 || mll.getState() == 2) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行申请退款操作");
            return returnbean;
        }

        //获取支入支出表---用户
        MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());

        //获取支入支出表---律师
        MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());

        try {
            //更新订单信息
            MfflLawyerletter mllr = new MfflLawyerletter();
            mllr.setId(id);
            //mllr.setState(5);     //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mllr.setPayState(3);    //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            mfflLawyerletterDao.update(mllr);

            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(3);//0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);  //获取支入支出表---用户

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(3);//0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);

            //修改订单信息
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(mo.getId());
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(4);//0待支付，1支付，2退款 , 4申请退款
            mfflOrderDao.update(mfflOrder);

            //新增退款信息
            MfflRefund byorderId = mfflRefundDao.getByorderId(mo.getId());
            if (byorderId == null) {
                MfflRefund refund = new MfflRefund();
                refund.setUserid(mo.getUserid());
                refund.setImplementid(0);
                refund.setOrderid(mo.getId().intValue());
                refund.setPaynumber(mo.getPayNumber());
                refund.setPaymerchantnumber(mo.getPayMerchantNumber());
                refund.setRefundnumber(mo.getPayNumber());
                refund.setRefundreason(refundreason);
                refund.setRefundstate(0);
                refund.setMoney(mo.getMoney());
                refund.setActualamount(mo.getMoney());
                Date date = new Date();
                refund.setRefundtime(date);
                refund.setCreateTime(date);
                refund.setUpdateTime(date);
                refund.setConfirmrefundtim(date);
                refund.setRefundname(mo.getServiceName());
                mfflRefundDao.save(refund);
            } else {
                MfflRefund refund = new MfflRefund();
                refund.setId(byorderId.getId());
                refund.setRefundreason(refundreason);
                refund.setRefundstate(0);
                Date date = new Date();
                refund.setRefundtime(date);
                refund.setUpdateTime(date);
                mfflRefundDao.update(refund);
            }
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]用户申请退款发布", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            return returnbean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("申请退款异常");
        }
    }


    /**
     * 取消申请退款
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean cancelRefund(Long id) throws Exception {
        ReturnBean returnbean = new ReturnBean();

        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id);
        if (mll == null) {
            return new ReturnBean("201", "合同不存在");
        }

        if (mll.getUserId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "合同不属于本用户");
        }

        //判断当前状态状态
        if (mll.getState() != 2) {
            return new ReturnBean("201", "当前状态非申请退款状态，无法取消");
        }

        try {
            //更新律师函信息
            MfflLawyerletter mllr = new MfflLawyerletter();
            mllr.setId(id);
            // mllr.setState(5);    //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款")
            mllr.setPayState(1);    //0待支付，1支付，2申请退款(退款中)，3已经退款
            mllr.setUpdateTime(new Date());
            mfflLawyerletterDao.update(mllr);

            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());
            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), sysUser.getId().intValue());
            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());

            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(1);//0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);  //获取支入支出表---用户
            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(0);//0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);
            //修改订单信息
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(mo.getId());
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(1);//0待支付，1支付，2退款 , 4申请退款
            mfflOrderDao.update(mfflOrder);
            //修改退款订单
            MfflRefund byorderId = mfflRefundDao.getByorderId(mo.getId());
            MfflRefund refund = new MfflRefund();
            refund.setId(byorderId.getId());
            refund.setRefundstate(2);
            refund.setUpdateTime(new Date());
            mfflRefundDao.update(refund);
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]用户取消申请退款", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            return returnbean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("申请退款异常");
        }
    }


    /**
     * 律师拒绝接受律师函服务
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean refuse(Integer id) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();

        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        //判断当前律师是否，是负责当前律师函的律师
        if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "当前律师不是,负责此律师函的律师");
        }

        //判断律师函状态
        if (mll.getState() != 0 && mll.getPayState() == 1) {
            returnbean.setErrCode("119");
            returnbean.setMessage("当前状态，不允许进行拒绝接受合同服务操作");
            return returnbean;
        }

        try {
            //获取订单信息
            MfflOrder mo = mfflOrderDao.getBypaymerchantnumber(mll.getPayMerchantNumber());
            //退款操作
            ReturnBean returnBean = wxpayservice.weChatrefund(mo.getPayMerchantNumber(), null, "律师拒绝服务", 0);
            if (!"200".equals(returnBean.getErrCode())) {
                return returnBean;
            }

            //更新律师函信息
            MfflLawyerletter mllr = new MfflLawyerletter();
            mllr.setId(id.longValue());
            mllr.setState(2);           //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
            mllr.setPayState(2);        //支付状态:0.待支付1.已支付2.已退款3.申请退款
            mllr.setUpdateTime(new Date());
            mfflLawyerletterDao.update(mllr);


            //获取支入支出表---用户
            MfflProfit userProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getUserId().intValue());

            //获取支入支出表---律师
            MfflProfit lawyerProfit = mfflProfitDao.getByOrderId(mo.getId().intValue(), mll.getServiceLawyerId());


            //修改双方支付支出表--用户
            MfflProfit mp = new MfflProfit();
            mp.setId(userProfit.getId());
            mp.setSettlement(2);        //0未结算，1已经算 ， 2退款，3 申请退款
            mp.setUpdateTime(new Date());
            mfflProfitDao.update(mp);

            //修改双方支付支出表--律师
            MfflProfit mlp = new MfflProfit();
            mlp.setId(lawyerProfit.getId());
            mlp.setSettlement(2);          //0未结算，1已经算 ， 2退款，3 申请退款
            mlp.setUpdateTime(new Date());
            mfflProfitDao.update(mlp);

            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]律师拒绝服务", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getUserId());
            return returnbean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("律师拒绝服务异常");
        }
    }


    /**
     * 评论
     *
     * @param comment 评论内容
     * @param rank    评论级别 1好评 2中评 3差评
     * @param id      律师函id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnBean comment(String comment, Integer rank, Integer id) throws Exception {
        ReturnBean returnBean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();

        //律师函是否存在
        MfflLawyerletter mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }

        if (mll.getUserId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "律师函不属于本用户");
        }

        if (mll.getCommentState() == 1) {
            return new ReturnBean("201", "已评论过了，无需重复评论");
        }

        if (mll.getState() != 3) {
            return new ReturnBean("201", "订单不是完成状态，无法评论");
        }

        try {
            MfflLawyerletter mllr = new MfflLawyerletter();
            mllr.setId(mll.getId());
            mllr.setCommentState(1);    //是否0未评论1评论
            mllr.setUpdateTime(new Date());
            mfflLawyerletterDao.update(mllr);

            //新增评论
            mfflLawyercommentservice.LawyerComment(comment, rank, mll.getUserId(), mll.getServiceLawyerId(), mll.getTypeId());
            //推送
            //MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]用户已评论", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
            return returnBean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("评论异常");
        }
    }


    /**
     * 律师确认接单
     *
     * @param id 合同id
     * @return
     */
    public ReturnBean confirm(Integer id) {
        ReturnBean returnBean = new ReturnBean();
        //获取当前用户
        SysUser sysUser = UserUtil.getLoginUser();
        //律师函是否存在
        MfflLawyerletterVo mll = mfflLawyerletterDao.getById(id.longValue());
        if (mll == null) {
            return new ReturnBean("201", "律师函不存在");
        }
        //判断当前律师是否，是负责当前合同的律师
        if (mll.getServiceLawyerId() != sysUser.getId().intValue()) {
            return new ReturnBean("201", "当前律师不是,负责此律师函的律师");
        }

        if (mll.getState() != 0) {
            returnBean.setErrCode("119");
            returnBean.setMessage("当前状态，不允许进行律师确认接单操作");
            return returnBean;
        }


        //查看律师是否通过认证
        MfflUser userInfoAll = mffluserdao.getmffluser(sysUser.getId().intValue());
        if (userInfoAll.getLawyerInspect() != 1) {
            returnBean.setReturnBean("137");
            return returnBean;
        }

        MfflLawyerletter mllr = new MfflLawyerletter();
        mllr.setId(mll.getId());
        mllr.setState(1);    //订单状态:0.发布成功1.已接单2.拒绝接单3.已发货4.完成交易5.已撤销订单6.超时接单撤销,自动退款7.已退款
        mllr.setUpdateTime(new Date());
        mfflLawyerletterDao.update(mllr);
        //判断用户是填写完整收货地址
        if (StringUtils.isEmpty(mll.getAddRessee()) || StringUtils.isEmpty(mll.getRecipientPhoneNumber()) || StringUtils.isEmpty(mll.getAddress())) {
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]请完善收货地址", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getUserId());
        }
        MfflSystemMessagesImpl.sendMessage(publicService.MessageModel("[律师函]律师确认接单", mll.getPayMerchantNumber()), mll.getServiceId().toString(), mll.getId().intValue(), mll.getServiceLawyerId());
        return returnBean;
    }


    /**
     * 关系咨询同时关闭订单
     *
     * @param id 咨询id
     */
    @Transactional
    public void delLetterAndOrder(Long id) {
        mfflLawyerletterDao.delete(id);
        mfflOrderDao.deleteOrderByProductId(id);
    }


    /**
     * 获取定时任务要处理的数据
     *
     * @return
     */
    public List<MfflLawyerletter> getTimerTaskData(Long ConfirmTime, Long RefuseTime) {
        return mfflLawyerletterDao.getTimerTaskData(ConfirmTime, RefuseTime);
    }

    /**
     * 修改
     *
     * @param mfflLawyerletter
     * @return
     */
    public int update(MfflLawyerletter mfflLawyerletter) {
        return mfflLawyerletterDao.update(mfflLawyerletter);
    }
}
